package datastructure.stackAndQueue;

public class LinkedQueue implements Queue {
	
	private SLLNode front, rear;
	private int count;
	
	
	public LinkedQueue(){
		clear();
	}
	
//Inner class
	
	private static class SLLNode {
		Object data;
		SLLNode next;
		
		SLLNode(){}
		
		SLLNode(Object obj){
			data = obj;
		}
		
//		SLLNode(Object obj,SLLNode link){
//			data = obj;
//			next = link;
//		}
		public void setNext(SLLNode link){
			next = link;
		}
		
		public String toString(){
			return data.toString();
		}
	}
	public void clear() {
		front = rear = null;
		count = 0;
	}

	public Object dequeue() {
		if(count==0){
			try {
				throw new IllegalQueueException();
			} catch (IllegalQueueException e) {
				e.printStackTrace();
			}
		}
		Object val = front.data;
		front = front.next;
		if(front==null)
			rear = null;
		count--;
		return val;
	}

	public void enqueue(Object val) {
		SLLNode node = new SLLNode(val);
		if(front==null)
			front = node;
		else
			rear.setNext(node);
		rear = node;
		count++;
	}

	public boolean isEmpty() {
		return count==0;
	}

	public Object peek() {
		if(count==0){
			try {
				throw new IllegalQueueException();
			} catch (IllegalQueueException e) {
				e.printStackTrace();
			}
		}
		return front.data;
	}

	public int size() {
		return count;
	}
	
	public String toString(){
		if(count==0)
			return "[]";
		StringBuffer buf = new StringBuffer("[");
		
		for(SLLNode curr = front;curr!=null;curr=curr.next)
			buf = buf.append(curr.data).append(",");
		buf.setCharAt(buf.length()-1, ']');
		return buf.toString();
	}

}
